import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Card, Col, Popconfirm, Row } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import * as c from '@/services/consts';
import * as api from '@/services/paramUpdate';
import { PageContainer, ProForm, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd/lib';
import * as utils from '@/utils/utils';

const ParamUpdategList: React.FC = () => {
  // const [formVisible, setFormVisible] = useState<boolean>(false);
  // const [current, setCurrent] = useState<API.TagModel | undefined>(undefined);

  const [originalValue, setOriginalValue] = useState<string | undefined>(undefined);
  const [newValue, setNewValue] = useState<string | undefined>(undefined);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  // const { hasRight } = useModel('useAuthModel');

  const { reloadAreaFilters } = useModel(
    'useGlobalModel',
    (model) => ({
      reloadAreaFilters: model.reloadAreaFilters,
    }),
  );


  const handleFormSubmit = async () => {
    if(!originalValue || originalValue.length < 4){
      message.error('请输入正确的原始内容');
      return;
    }
    
    if(!newValue || newValue.length < 4){
      message.error('请输入正确的原始内容');
      return;
    }

    let result = await api.update({originalValue, newValue});

    if (result && result.success === true) {
      message.success('替换成功');
      actionRef.current?.reload();

      await reloadAreaFilters();
    }
  };
  
  
  const handleSearchReplace = async () => {
    let tmpOriginalValue = formRef.current?.getFieldValue('originalValue');
    let tmpNewValue = formRef.current?.getFieldValue('newValue');

    if(!tmpOriginalValue || tmpOriginalValue.length < 4){
      message.error('请输入正确的原始内容');
      return;
    }
    
    if(!tmpNewValue || tmpNewValue.length < 4){
      message.error('请输入正确的原始内容');
      return;
    }

    setOriginalValue(tmpOriginalValue);
    setNewValue(tmpNewValue);
    actionRef.current?.reload();
  };

  let columns: ProColumns<API.ParamUpdate>[] = [
    {
      title: '类型',
      dataIndex: 'tableTitle',
      width: 100,
      sorter: true,
    },
    {
      title: '名称',
      dataIndex: 'rowTitle',
      width: 100,
      sorter: true,
    },
    {
      title: '项目',
      dataIndex: 'rowName',
      width: 120,
      sorter: true,
    },
    {
      title: '原始内容',
      dataIndex: 'originalValue',
      render: (_, record) => {
        return record.originalValue ? <div dangerouslySetInnerHTML={{__html:utils.highlight(record.originalValue, originalValue).replaceAll('\n', '<br>')}}></div>
         : '';
      },
    },
    {
      title: '替换内容',
      dataIndex: 'newValue',
      render: (_, record) => {
        return record.newValue ? <div dangerouslySetInnerHTML={{__html:utils.highlight(record.newValue, newValue).replaceAll('\n', '<br>')}}></div>
         : '';
      },
    },
  ];

  return (
    <PageContainer>
          <ProForm
            formRef={formRef}
            layout="horizontal"
            submitter={{
              render: (props, doms) => {
                return [];
              },
            }}
            // onFinish={handleFormSubmit}
          >
            <Row gutter={24}>
              <Col span={8}>
                <ProFormText
                  name='originalValue'
                  label="原始内容"
                  rules={[{ required: true, message: '请输入原始内容' }]}
                />
              </Col>
              <Col span={8}>
                <ProFormText
                  name='newValue'
                  label="替换内容"
                  rules={[{ required: true, message: '请输入替换内容' }]}
                />
              </Col>
              <Col span={8}>
                <Button
                  type="primary"
                  key="searchReplace"
                  onClick={async () => {
                    await handleSearchReplace();
                  }}
                >
                  查找项目
                </Button>　     
                
                <Popconfirm
                  key="submitReplace"
                  title="确定要替换内容吗?"
                  onConfirm={async () => {
                    await handleFormSubmit();
                  }}
                  disabled={!originalValue || !newValue}
                >
                  <Button type="primary" danger disabled={!originalValue || !newValue}>替换内容</Button>
                </Popconfirm>

              </Col>
            </Row>
          </ProForm>

      <ProTable
        rowKey="id"
        actionRef={actionRef}
        cardProps={{ bodyStyle: { padding: 0 } }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        headerTitle={<>
        </>}
        search={false}
        pagination={false}
        // toolbar={{
        //   filter: (
        //     <LightFilter>
        //       <ProFormSelect
        //         name="type"
        //         label="标签类型"
        //         options={c.TagTypeOptions}
        //         fieldProps={{
        //           onChange: (value) => {
        //             setTagType(value ? value : '');
        //           },
        //         }}
        //       />
        //     </LightFilter>
        //   ),
        //   menu: {
        //     type: 'tab',
        //     activeKey: productId,
        //     items: productMenuItems,
        //     onChange: (tabKey) => {
        //       //console.log('tabKey', tabKey);
        //       setProductId(tabKey as string);
        //     },
        //   },
        // }}
        // toolBarRender={() => {
        //   if (hasRight('tag_create')) {
        //     return [
        //       <Button
        //         type="primary"
        //         key="create"
        //         onClick={() => {
        //           setFormVisible(true);
        //         }}
        //       >
        //         <PlusOutlined /> 新建
        //       </Button>,
        //     ];
        //   }
        //   return [];
        // }}
        columns={columns}
        params={{
          originalValue,
          newValue,
        }}
        request={api.list}
      />

    </PageContainer>
  );
};

export default ParamUpdategList;
